#include "dxtexture.h"
#include "graphic.h"
#include "dxrendersystem.h"
#include "archivemanager.h"

#ifdef _DEBUG
#ifdef _MSC_VER
   #define new new( _CLIENT_BLOCK, __FILE__, __LINE__)
#endif
#endif // _DEBUG

namespace Engine
{
	/**********************************************************************************************************/
	DXTexture* DXTextureFactory::CreateInstance( const std::string& name )
	{
		return new DXTexture(name);
	}
	/**********************************************************************************************************/
	DXTexture::DXTexture(const std::string& name):Texture(name)
	{
	}
	/**********************************************************************************************************/
	DXTexture::~DXTexture()
	{
	}
	/**********************************************************************************************************/
	void DXTexture::Load()
	{
		if(IsLoaded())
			return;
		RefPtr<DataStream> file = ArchiveManager::GetSingleton().ReadFile(GetName());
		if(!file.IsNull())
		{

			size_t len = file->GetSize();
			RefPtr<char,NoWeakPtrExtension,ArrayDelete> buf(new char[len]);
			len = file->Read(buf.GetPointer(),len);

			IDirect3DTexture9* tex = NULL;

			DXRenderSystem* renderSystem = static_cast<DXRenderSystem*>(Graphic::GetSingleton().GetRenderSystem().GetPointer());
			if(FAILED(D3DXCreateTextureFromFileInMemoryEx(renderSystem->GetDirect3DGlobals()->d3dDevice.GetPointer(),buf.GetPointer(),len,D3DX_DEFAULT,D3DX_DEFAULT,D3DX_DEFAULT,0,D3DFMT_A8R8G8B8,D3DPOOL_MANAGED,D3DX_DEFAULT,D3DX_DEFAULT,0,NULL,NULL,&tex)))
				throw std::logic_error("Can't create d3d texture" + GetName());
			m_texture = ComPtr<IDirect3DTexture9>(tex);
			SetLoaded(true);
		}
		else
			throw std::logic_error("Can't load texture file" + GetName());
	}
	/**********************************************************************************************************/
	void DXTexture::UnLoad()
	{
		m_texture.Delete();
		SetLoaded(false);
	}
	/**********************************************************************************************************/
	IDirect3DTexture9* DXTexture::GetTexture()
	{
		return m_texture.GetPointer();
	}
	/**********************************************************************************************************/
}
